package com.sgb.member.ui.activity;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.text.TextUtils;
import android.view.View;

import androidx.databinding.DataBindingUtil;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;

import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.sgb.member.MemberConfig;
import com.sgb.member.R;
import com.sgb.member.databinding.ActivityMemberTransferBinding;
import com.sgb.member.entity.ApplyCompanyBean;
import com.sgb.member.entity.CompanyDeptBean;
import com.sgb.member.entity.MemberBean;
import com.sgb.member.entity.MemberUpdateLevelBean;
import com.sgb.member.entity.ParamDtosEntity;
import com.sgb.member.event.EventConstant;
import com.sgb.member.event.MemberEvent;
import com.sgb.member.util.ChooseFileUtil;
import com.sgb.member.weight.AppendFieldsView;
import com.sgb.member.weight.MemberCommonDialog;
import com.sgb.member.weight.SimpleResult;
import com.sgb.member.weight.UploadFileBean;
import com.swgk.core.base.AppActivity;
import com.swgk.core.base.model.entity.BaseEntity;
import com.swgk.core.customview.ItemInputTextView;
import com.swgk.core.dialog.DialogHelper;
import com.swgk.core.util.LogUtil;
import com.swgk.core.util.MToast;
import com.swgk.core.util.SharedPreferenceUtil;
import com.swgk.core.view.selection.CommonPopEntity;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;

/**
 * 会员调级申请
 */
public class MemberTransferActivity extends AppActivity implements ItemInputTextView.OnWholeItemClickListener {

    private ActivityMemberTransferBinding mBinding;
    private MemberTransferModel sModel;
    private MemberBean memberBean;
    private int mCurPos; // 会员管理需方、供方会员列表跳转下标 -1：会员企业店铺跳转标识

    private OptionsPickerView<CommonPopEntity> mOption;
    private OptionsPickerView<CompanyDeptBean> mOptionDept;

    // 调级申请Bean类
    private MemberUpdateLevelBean levelBean;
    private String companyId = "";

    private boolean hasApproval;// 是否有审批

    /**
     * MemberBean bean = new MemberBean();
     * bean.setNo("");
     * bean.setCompanyNo("");
     * bean.setCompanyName("");
     * bean.setMemberUpdateLeverType(""); //1供方会员 2需方会员
     * bean.setLevel("");
     * bean.setCheckType(2); // // 1 个人 2 企业
     */
    public static void start(Context context, MemberBean bean, int pos) {
        Intent intent = new Intent(context, MemberTransferActivity.class);
        intent.putExtra("Bean", bean);
        intent.putExtra("Position", pos);
        context.startActivity(intent);
    }

    @Override
    protected boolean statusBarDark() {
        return true;
    }

    @Override
    protected void initView() {
        memberBean = (MemberBean) getIntent().getSerializableExtra("Bean");
        mCurPos = getIntent().getIntExtra("Position", 0);
        mBinding = DataBindingUtil.setContentView(this, R.layout.activity_member_transfer);
        sModel = new ViewModelProvider(this).get(MemberTransferModel.class);
        mBinding.setLifecycleOwner(this);
        mBinding.setViewModel(memberBean);
        mBinding.activityBar.titleView.setText("会员调级申请");
        mBinding.activityBar.ivBack.setOnClickListener(v -> finish());
        registerObserver();
    }

    @Override
    protected void init() {
        mBinding.itemInputName.setMemberStyle();
        mBinding.itemInputCompanyName.setMemberStyle();
        mBinding.itemInputLever.setMemberStyle();
        mBinding.itemInputLeverSetting.setMemberStyle();

        mBinding.itemInputLeverSetting.setOnWholeItemClickListener(this);
        mBinding.itemInputDepartment.setOnWholeItemClickListener(this);

        mBinding.submit.setOnClickListener(this);
        initUserInfo();
    }

    private void initUserInfo() {
        String userName = SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.REAL_NAME, "");
        String userNo = SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.USER_NO, "");
        String companyName = SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.COMPANY_NAME, "");
        String companyNo = SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.COMPANY_NO, "");
        mBinding.itemInputName.setContent(userName);
        mBinding.itemInputCompanyName.setContent(memberBean.getCompanyName());
        mBinding.itemInputLever.setContent(memberBean.getLevel());
        levelBean = new MemberUpdateLevelBean();
        levelBean.setNo(memberBean.getNo());
        levelBean.setMemberType(memberBean.getMemberUpdateLeverType()); // 1供方会员 2需方会员
        levelBean.setCheckType(memberBean.getCheckType());
        // 申请人信息
        levelBean.setApplyUserName(userName);
        levelBean.setApplyUserNo(userNo);
        levelBean.setApplyCompanyName(companyName);
        levelBean.setApplyCompanyNo(companyNo);
        //调级企业
        if (levelBean.isPersonMember()) {
            levelBean.setCustomUserName(memberBean.getCompanyName());
            levelBean.setCustomUserNo(memberBean.getCompanyNo());
        } else {
            levelBean.setCustomCompanyName(memberBean.getCompanyName());
            levelBean.setCustomCompanyNo(memberBean.getCompanyNo());
        }
        levelBean.setLevel(memberBean.getLevel());

        sModel.getMyCompanyList();
    }

    private void registerObserver() {
        sModel.dialog.observe(this, aBoolean -> {
            if (aBoolean) {
                if (!DialogHelper.isShowing()) {
                    DialogHelper.showProgressDialog(MemberTransferActivity.this, "数据获取中...");
                }
            } else {
                DialogHelper.dismissProgressDialog();
            }
        });
        sModel.userInfo.observe(this, new Observer<Boolean>() {
            @Override
            public void onChanged(Boolean aBoolean) {
                if (aBoolean) {
                    initUserInfo();
                } else {
                    finish();
                }
            }
        });
        sModel.mLevers.observe(this, this::showLeverPop);
        sModel.mCompanyList.observe(this, new Observer<List<ApplyCompanyBean>>() {
            @Override
            public void onChanged(List<ApplyCompanyBean> applyCompanyBeans) {
                if (TextUtils.isEmpty(companyId)) {
                    for (ApplyCompanyBean applyCompanyBean : applyCompanyBeans) {
                        if (applyCompanyBean.getComNo().equals(levelBean.getApplyCompanyNo())) {
                            companyId = applyCompanyBean.getId();
                            return;
                        }
                    }
                }
            }
        });
        sModel.mDepList.observe(this, new Observer<List<CompanyDeptBean>>() {
            @Override
            public void onChanged(List<CompanyDeptBean> companyDeptBeans) {
                if (companyDeptBeans != null && companyDeptBeans.size() > 0) {
                    showDeptPop(companyDeptBeans);
                } else {
                    MToast.showToast(MemberTransferActivity.this, "申请部门暂时为空.");
                }
            }
        });
        sModel.mApprovalStatus.observe(this, new Observer<String>() {
            @Override
            public void onChanged(String status) {
                hasApproval = false;
                if (!TextUtils.isEmpty(status)) {
                    if ("1".equals(status)) {
                        hasApproval = true;
                        MemberCommonDialog dialog = new MemberCommonDialog(new MemberCommonDialog.SimpleListener() {
                            @Override
                            public void onPositive(Object... objects) {
                                sModel.memberUpdateLevel(levelBean);
                            }
                        }, MemberCommonDialog.STYLE_CONFIRM_APPROVAL);
                        dialog.show(MemberTransferActivity.this, "MemberCommonDialog");
                    } else {
                        sModel.memberUpdateLevel(levelBean);
                    }
                } else {
                    MToast.showToast(getActivity(), "网络异常，请稍后重试");
                }
            }
        });
        // 有审批：点击弹窗提示：确认发起审批当前业务，点击“取消”，隐藏对话框，点击“确定”，跳转至待办-我发起的列表栏
        // 无审批：点击后吐司提示：调级成功，并返回底层列表
        sModel.mUpdateLevel.observe(this, new Observer<BaseEntity<Object>>() {
            @Override
            public void onChanged(BaseEntity<Object> entity) {
                if ("0".equals(entity.getCode())) {
                    if (hasApproval) {
                        MToast.showToast(MemberTransferActivity.this, "会员调级申请成功");
                        // 跳转至页面用户中心-审批列表-我发起的
                        MemberConfig.getInstance().startApprovalManager(MemberTransferActivity.this, 1);
                    } else {
                        MToast.showToast(MemberTransferActivity.this, "会员调级成功");
                        // 会员调级成功，发送事件通知更新数据
                        memberBean.setLevel(levelBean.getGrade());
                        EventBus.getDefault().postSticky(MemberEvent.make()
                                .setMessageTag(EventConstant.EVENT_MEMBER_UPDATE_LEVEL)
                                .setMessageData(memberBean)
                                .setPos(mCurPos)
                        );
                    }
                    finish();
                } else {
                    MToast.showToast(MemberTransferActivity.this, entity.getMsg());
                }
            }
        });
        sModel.mFileData.observe(this, new Observer<UploadFileBean>() {
            @Override
            public void onChanged(UploadFileBean uploadFileBean) {
                mBinding.uploadLayout.addData(uploadFileBean);
            }
        });
    }

    @SuppressLint("NonConstantResourceId")
    @Override
    public void OnWholeItemClick(View view) {
        int id = view.getId();
        if (id == R.id.item_input_lever_setting) {
            if (sModel.mLevers.getValue() == null || sModel.mLevers.getValue().size() == 0) {
                sModel.getMemberLevelList();
                return;
            }
            showLeverPop(sModel.mLevers.getValue());
        } else if (id == R.id.item_input_department) {
            if (sModel.mDepList.getValue() == null || sModel.mDepList.getValue().size() == 0) {
                if (TextUtils.isEmpty(companyId)) {
                    sModel.getMyCompanyList();
                } else {
                    sModel.getDeptList(companyId);
                }
                return;
            }
            showDeptPop(sModel.mDepList.getValue());
        }
    }

    @Override
    public void onMultiClick(View v) {
        if (v.getId() == R.id.submit) {
            if (TextUtils.isEmpty(mBinding.etOpinion.getContent())) {
                MToast.showToast(this, "请填写300字以内综合意见");
                return;
            }
            if (TextUtils.isEmpty(mBinding.itemInputLeverSetting.getContent())) {
                MToast.showToast(this, "请选择会员等级");
                return;
            }
            if (mBinding.itemInputLeverSetting.getContent().equals(memberBean.getLevel())) {
                MToast.showToast(this, "与当前会员等级一致，请重新设置");
                return;
            }
            String achievement = mBinding.etPerformance.getContent();
            if (!TextUtils.isEmpty(achievement)) {
                levelBean.setAchievement(achievement);
            }
            String specialAssets = mBinding.etSpecialAssets.getContent();
            if (!TextUtils.isEmpty(specialAssets)) {
                levelBean.setSpecialAssets(specialAssets);
            }
            String professional = mBinding.etProfessional.getContent();
            if (!TextUtils.isEmpty(professional)) {
                levelBean.setProfessional(professional);
            }
            String manager = mBinding.etManager.getContent();
            if (!TextUtils.isEmpty(manager)) {
                levelBean.setManagementSystem(manager);
            }
            String structure = mBinding.etStructure.getContent();
            if (!TextUtils.isEmpty(structure)) {
                levelBean.setOrganizationStructure(structure);
            }
            String corporateCulture = mBinding.etCorporateCulture.getContent();
            if (!TextUtils.isEmpty(corporateCulture)) {
                levelBean.setCorporateCulture(corporateCulture);
            }
            String integrityReview = mBinding.etIntegrityReview.getContent();
            if (!TextUtils.isEmpty(integrityReview)) {
                levelBean.setSincerity(integrityReview);
            }
            levelBean.setOpinion(mBinding.etOpinion.getContent());
            // 自定义参数
            List<AppendFieldsView.AppendField> data = mBinding.fieldsLayout.getData();
            List<ParamDtosEntity> paramDtos = new ArrayList<>();
            if (data != null && data.size() > 0) {
                for (AppendFieldsView.AppendField datum : data) {
                    if (!TextUtils.isEmpty(datum.title) && !TextUtils.isEmpty(datum.content)) {
                        paramDtos.add(new ParamDtosEntity(datum.title, datum.content));
                    }
                }
            }
            levelBean.setParamDtos(paramDtos);
            // 附件列表
            List<UploadFileBean> fileList = mBinding.uploadLayout.getData();
            List<String> temFileList = new ArrayList<>();
            if (fileList != null && fileList.size() > 0) {
                for (UploadFileBean uploadFileBean : fileList) {
                    temFileList.add(uploadFileBean.getUrlPath());
                }
            }
            levelBean.setFileList(temFileList);
            // 有审批：点击弹窗提示：确认发起审批当前业务，点击“取消”，隐藏对话框，点击“确定”，跳转至待办-我发起的列表栏
            // 无审批：点击后吐司提示：调级成功，并返回底层列表
            sModel.getProcessStatus();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == MemberConfig.REQ_FILE_CHOOSE) {//选择文件返回
                if (data == null) {
                    LogUtil.d("TAG", "onActivityResult chooseFile data is null");
                    return;
                }
                ChooseFileUtil.handleFileChoose(getActivity(), data, new SimpleResult<UploadFileBean>() {
                    @Override
                    public void onResult(UploadFileBean uploadFileBean, Object... objects) {
                        List<UploadFileBean> beans = mBinding.uploadLayout.getData();
                        if (beans != null && beans.size() > 0) {
                            for (UploadFileBean bean : beans) {
                                if (bean.getFilePath().equals(uploadFileBean.getFilePath())) {
                                    MToast.showToast(MemberTransferActivity.this, "该文件已上传！");
                                    return;
                                }
                            }
                        }
                        sModel.uploadSingleFile(uploadFileBean);
                    }
                });
            }
        }
    }

    public void showLeverPop(List<CommonPopEntity> optionData) {
        if (mOption == null) {
            mOption = new OptionsPickerBuilder(this, (options1, options2, options3, v) -> {
                String name = optionData.get(options1).getTypeName();
                mBinding.itemInputLeverSetting.setContent(name);
                // 设置会员等级
                levelBean.setGrade(name);
            }).build();
            mOption.setTitleText("会员等级");
        }
        mOption.setPicker(optionData);
        mOption.setSelectOptions(0);
        mOption.show();
    }

    // 选择部门
    public void showDeptPop(List<CompanyDeptBean> mOptionData) {
        if (mOptionDept == null) {
            mOptionDept = new OptionsPickerBuilder(this, (options1, options2, options3, v) -> {
                String name = mOptionData.get(options1).getName();
                String id = mOptionData.get(options1).getId();
                mBinding.itemInputDepartment.getContent_edt().setText(name);
                // 申请部门
                levelBean.setApplyDeptNo(id);
                levelBean.setApplyDeptName(name);
            }).setCancelColor(getResources().getColor(R.color.color_title_small)).build();
            mOptionDept.setTitleText("申请部门");
        }
        mOptionDept.setPicker(mOptionData);
        mOptionDept.setSelectOptions(0);
        mOptionDept.show();
    }
}
